package com.webserver.http;

import java.io.*;
import java.net.Socket;

/*
    响应对象：
    该类的每一个实例用于表示一个响应，每个箱应有三部分构成
    1：状态行
    2：响应头
    3：响应正文
 */
public class HttpServletResponse {


    private int statusCode= 200;
    private String statusReason = "OK";

    //响应正文相关信息
    private File entity;//响应正文对应的实体文件


    private Socket socket;

    //响应正文相关信息

    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }


    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public File getEntity() {
        return entity;
    }

    public void setEntity(File entity) {
        this.entity = entity;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public void response() throws IOException {
        OutputStream out = socket.getOutputStream();

        //3.1发送状态行:
        sendStatusLine();

        //3.2发送响应头:
        sendHeaders();

        //3.3发送响应正文:
        sendContent();

        System.out.println("响应发送完毕");

    }

    private void sendStatusLine() throws IOException {//发送状态行
        String line = "HTTP/1.1 200 OK";
        println(line);

    }
    //发送响应头:
    private void sendHeaders() throws IOException {
        String  line = "Content-Type: text/html";
        println(line);

        line = "Content-Length: " + entity.length();
        println(line);

        //单独发送CRLF表示响应头部分发送完毕
        println("");
    }

    private void sendContent() throws IOException {//发送响应正文
        FileInputStream fis = new FileInputStream(entity);
        int len;
        byte[] buf = new byte[1024*10];
        OutputStream out = socket.getOutputStream();
        while((len = fis.read(buf))!=-1){
            out.write(buf,0,len);
        }
    }

    //发送一行字符串
    private void println(String line) throws IOException {
        byte[] data = line.getBytes("ISO8859-1");
        OutputStream out = socket.getOutputStream();
        out.write(data);
        out.write(13);//发送一个回车符
        out.write(10);//发送一个换行符
    }

}
